package com.dst.note.note_edit;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.dst.note.BaseActivity;
import com.dst.note.ClockManager;
import com.dst.note.ClockService;
import com.dst.note.model.Note;
import com.dst.note.model.Voice;
import com.jscheng.annotations.Route;
import com.dst.note.R;
import com.dst.note.constatns.FileDir;
import com.dst.note.editor.NoteEditorClickListener;
import com.dst.note.editor.NoteEditorText;
import com.dst.note.outline.RecordAudioDialogFragment;
import com.dst.note.utils.BitmapUtils;
import com.dst.note.utils.FileType;
import com.dst.note.utils.FileUtils;
import com.dst.note.utils.KeyboardUtil;
import com.dst.note.utils.PermissionUtil;
import com.dst.note.utils.PhotoUtils;
import com.dst.note.utils.UriPathUtil;
import com.dst.note.utils.ViewToBmp;
import com.dst.note.widget.CircularProgressView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * 编辑页
 * Created By tgl on 2019/2/21
 */
@Route("editnote")
public class EditNoteActivity extends BaseActivity implements EditNotePresenter.EditNoteView, NoteEditorClickListener {
    private final static int ACTION_PICK_CODE = 1;
    private final static int PERMISSION_CODE = 2;
    private final static int PERMISSION_CODE_AUDIO = 3;
    private final static int REQUEST_CODE = 4;

    private EditNoteToolbar mToolbar;
    private EditNotePresenter mPresenter;
    private FloatEditButton mEditButton;
    private NoteEditorText mEditorText;
    private NoteEditorBar mEditorBar;
    private EditNoteFormatDialog mFormatDialog;
    private CircularProgressView mLoadingView;
    private ClockManager mClockManager = ClockManager.getInstance();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_editnote);
        mPresenter = new EditNotePresenter(getIntent()) {

            @Override
            public void voice() {
                if (PermissionUtil.isPermissionGranted(EditNoteActivity.this, Manifest.permission.RECORD_AUDIO)) {
                    final RecordAudioDialogFragment fragment = RecordAudioDialogFragment.newInstance();
                    fragment.show(getSupportFragmentManager(), RecordAudioDialogFragment.class.getSimpleName());
                    return;
                }
                requestPermissionAudio();
            }

            @Override
            public void addAlarm(String id, long time) {
                if (time == 0) {
                    return;
                }
                mClockManager.addAlarm(buildIntent(id), new Date(time));
            }

            @Override
            public void cancelAlarm() {
                super.cancelAlarm();
                mClockManager.cancelAlarm(buildIntent(getNoteid()));
            }

            @Override
            public void tapTakePhoto() {
                if (PermissionUtil.isPermissionGranted(EditNoteActivity.this, Manifest.permission.CAMERA)) {
                    PhotoUtils.openCamera(EditNoteActivity.this, REQUEST_CODE);
                    return;
                }
                requestPermissionAudio();
            }

            private PendingIntent buildIntent(String noteId) {
                Intent intent = new Intent();
                intent.putExtra(ClockService.EXTRA_EVENT_ID, noteId);
                intent.setClass(EditNoteActivity.this, ClockService.class);

                return PendingIntent.getService(EditNoteActivity.this, 0x001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
        };
        this.getLifecycle().addObserver(mPresenter);
        mEditButton = findViewById(R.id.float_edit_button);
        mEditButton.setPresenter(mPresenter);

        mLoadingView = findViewById(R.id.circular_progress);
        mLoadingView.setVisibility(View.GONE);

        mEditorText = findViewById(R.id.edit_note_editor);
        mEditorText.getStyleManager().addClickListener(this);

        mToolbar = findViewById(R.id.edit_note_toolbar);
        mToolbar.setPresenter(mPresenter);
        mToolbar.setStyleManager(mEditorText.getStyleManager());

        mEditorBar = findViewById(R.id.edit_note_bar);
        mEditorBar.setStyleManager(mEditorText.getStyleManager());
        mEditorBar.hide();

        //requestPermission();
        requestPermissionAudio();
    }

    @Override
    public void showLoading() {
        mLoadingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    public void apply(Note mNote, int selectionStart, int selectionEnd) {
        mEditorText.getStyleManager().apply(mNote, selectionStart, selectionEnd);
    }

    @Override
    public void writingMode(boolean isEditorBarEnable) {
        mEditorText.setHint("文字、图片、语音都可以哦！");
        mEditorText.writingMode();
        mToolbar.writingMode();
        mEditorBar.setVisibility(isEditorBarEnable ? View.VISIBLE : View.GONE);
        mToolbar.setFormatEnable(isEditorBarEnable);
        mEditButton.hide();
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    public void readingMode() {
        mEditorText.setHint("啥也没有，赶快记录吧！");
        mEditorText.readingMode();
        mToolbar.readingMode();
        mEditButton.show();
        mEditorBar.setVisibility(View.GONE);
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    public void loadingMode() {
        mEditorText.readingMode();
        mToolbar.readingMode();
        mEditButton.setVisibility(View.GONE);
        mEditorBar.setVisibility(View.GONE);
        mLoadingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onBackPressed() {
        mPresenter.tapBack();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void setEditorbar(boolean isEnable) {
        mEditorBar.setVisibility(isEnable ? View.VISIBLE : View.GONE);
        mToolbar.setFormatEnable(isEnable);
    }

    @Override
    public void showFormatDialog() {
        if (mFormatDialog == null) {
            mFormatDialog = new EditNoteFormatDialog(this, mPresenter);
        }
        KeyboardUtil.hideSoftInput(this, mEditorText);
        mFormatDialog.show();
    }

    @Override
    public void showAlbumDialog() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, ACTION_PICK_CODE);
    }

    @Override
    public void showNetworkDialog() {
        EditNoteInputDialog dialog = new EditNoteInputDialog(this, mPresenter);
        dialog.show();
    }

    @Override
    public void insertImage(String url) {
        mEditorText.getStyleManager().commandImage(url, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == ACTION_PICK_CODE) {
                Uri uri = data.getData();
                String path = UriPathUtil.getAbsulotePath(this, uri);
                insertImage(path);
            } else if (requestCode == REQUEST_CODE) {
                String path = data.getStringExtra("result"); // 图片地址
                if (TextUtils.isEmpty(path)) {
                    List<String> pathList = data.getStringArrayListExtra("result");
                    if (pathList == null || pathList.size() == 0) {
                        return;
                    }
                    path = pathList.get(0);
                }
                insertImage(path);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void requestPermission() {
        PermissionUtil.checkPermissionsAndRequest(this, PermissionUtil.STORAGE, PERMISSION_CODE, "请求访问SD卡权限被拒绝");
    }

    private void requestPermissionAudio() {
        PermissionUtil.checkPermissionsAndRequest(this, new String[]{
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        }, PERMISSION_CODE, "请求访问SD卡权限被拒绝");
    }

    @Override
    public void onClickImage(List<String> urls, int index) {
        String path = urls.get(index);
        if (path.endsWith(FileType.TYPE_VOICE_TO_IMG)) {
            mPresenter.startPlaying(this, path.replace(FileType.TYPE_VOICE_TO_IMG, ""));
        } else {
            mPresenter.tapImage(urls, index);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mPresenter.payerRelease();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void luYin(Voice voice) {
        if (voice != null && voice.path != null) {
            File file = new File(voice.path);
            if (file.exists() && file.length() > 0) {
                Bitmap bitmap = ViewToBmp.parseBmp(this, file);
                String path = FileUtils.getDiskDir(this, FileDir.DIR_VOICE) + File.separator + file.getName() + FileType.TYPE_VOICE_TO_IMG;
                if (BitmapUtils.saveBitmap(bitmap, path)) {
                    insertImage(path);
                }
            }
        }

    }
}
